package com.esheeper.mainserver.util;

import com.esheeper.mainserver.pojo.User;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.*;

public class CryptUtil {

    /**
     * 方法名
     *
     * @param originalPassword 原始密码串
     * @return 加密后并格式化后的密码串
     * @description 使用MD5不可逆加密，然后采用Base64方式格式化
     * @author Wenyang Su
     * @date 2023-05-16
     * @version 1.0.0
     */
    @Value("${crypt.md5.salt}")
    static String salt;
    @Value("${crypt.md5.logic-timestamp-provider-validate-salt}")
    static String logicTimestampProviderSalt;

    public static boolean validateToken(User user, String token, Date expires) throws NoSuchAlgorithmException {
        MessageDigest md5 = MessageDigest.getInstance("MD5");
        md5.update((user.getId() + user.getUsername() + salt + expires.toString()).getBytes());
        String hashedPwd = new BigInteger(1, md5.digest()).toString(16);
        Base64.Encoder encoder = Base64.getEncoder();
        return encoder.encodeToString(md5.digest()) == token;
    }

    public static String genLogicTimestampProviderToken(String randomString) throws NoSuchAlgorithmException {
        MessageDigest md5 = MessageDigest.getInstance("MD5");
        md5.update((randomString+logicTimestampProviderSalt).getBytes());
        String hashedPwd = new BigInteger(1, md5.digest()).toString(16);
        Base64.Encoder encoder = Base64.getEncoder();
        return encoder.encodeToString(md5.digest());
    }
}